import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getApiConfig, discoverWorkingServer, getFunctionServer, OPENAI_CONFIG } from '../config';

// 获取API配置
let apiConfig = getApiConfig();

// 调试信息
console.log('🔍 API配置信息:');
console.log('环境:', apiConfig);
console.log('基础URL:', apiConfig.baseURL);
console.log('超时时间:', apiConfig.timeout);

// 自动发现可用服务器
const initializeAPI = async () => {
  try {
    console.log('🚀 初始化API服务...');
    
    // 尝试发现可用服务器
    const workingServer = await discoverWorkingServer();
    if (workingServer) {
      apiConfig = getApiConfig(); // 重新获取配置
      console.log('✅ API服务初始化成功，使用服务器:', workingServer);
    } else {
      console.log('⚠️ 无法找到可用服务器，使用默认配置');
    }
  } catch (error) {
    console.log('❌ API服务初始化失败:', error);
  }
};

// 启动时初始化
initializeAPI();

// 创建axios实例
const api = axios.create({
  baseURL: apiConfig.baseURL,
  timeout: apiConfig.timeout,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 创建功能专用axios实例
const createFunctionAPI = (functionType: 'auth' | 'upload' | 'api') => {
  const serverUrl = getFunctionServer(functionType);
  console.log(`🔧 创建${functionType}专用API实例，使用服务器: ${serverUrl}`);
  
  return axios.create({
    baseURL: serverUrl,
    timeout: apiConfig.timeout,
    headers: {
      'Content-Type': 'application/json',
    },
  });
};

// 请求拦截器
api.interceptors.request.use(
  async (config) => {
    // 从本地存储获取token
    const token = await AsyncStorage.getItem('authToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    // 确保使用最新的baseURL
    if (config.baseURL !== apiConfig.baseURL) {
      config.baseURL = apiConfig.baseURL;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    if (error.response?.status === 401) {
      // Token过期，清除本地存储并跳转到登录页
      await AsyncStorage.removeItem('authToken');
      await AsyncStorage.removeItem('userData');
      // 这里可以触发重新登录的逻辑
    }
    return Promise.reject(error);
  }
);

// API方法
export const authAPI = {
  login: (email: string, password: string) => {
    console.log('🔐 尝试登录:', email);
    const authApi = createFunctionAPI('auth');
    return authApi.post('/auth/login', { email, password });
  },
  
  register: (name: string, email: string, password: string) => {
    console.log('📝 尝试注册:', { name, email });
    const authApi = createFunctionAPI('auth');
    return authApi.post('/auth/register', { name, email, password });
  },
  
  forgotPassword: (email: string) => {
    console.log('🔑 尝试忘记密码:', email);
    const authApi = createFunctionAPI('auth');
    return authApi.post('/auth/forgot-password', { email });
  },
  
  resetPassword: (token: string, password: string) => {
    console.log('🔄 尝试重置密码');
    const authApi = createFunctionAPI('auth');
    return authApi.post('/auth/reset-password', { token, password });
  },
  
  logout: () => {
    console.log('🚪 尝试登出');
    const authApi = createFunctionAPI('auth');
    return authApi.post('/auth/logout');
  },
  
  refreshToken: () => {
    console.log('🔄 尝试刷新Token');
    const authApi = createFunctionAPI('auth');
    return authApi.post('/auth/refresh-token');
  },
};

export const userAPI = {
  getProfile: () => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.get('/user/profile');
  },
  
  updateProfile: (data: any) => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.put('/user/profile', data);
  },
  
  changePassword: (oldPassword: string, newPassword: string) => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.put('/user/change-password', { oldPassword, newPassword });
  },
  
  uploadAvatar: (formData: FormData) => {
    const apiInstance = createFunctionAPI('upload'); // 头像上传使用上传服务器
    return apiInstance.post('/user/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
};

export const vehicleAPI = {
  // 获取车辆列表
  getVehicles: (params?: any) => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.get('/vehicles', { params });
  },
  
  // 获取单个车辆详情
  getVehicle: (id: string) => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.get(`/vehicles/${id}`);
  },
  
  // 创建车辆
  createVehicle: (data: any) => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.post('/vehicles', data);
  },
  
  // 更新车辆
  updateVehicle: (id: string, data: any) => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.put(`/vehicles/${id}`, data);
  },
  
  // 删除车辆
  deleteVehicle: (id: string) => {
    const apiInstance = createFunctionAPI('api');
    return apiInstance.delete(`/vehicles/${id}`);
  },
  
  // 上传车辆媒体文件
  uploadMedia: (vehicleId: string, formData: FormData) => {
    const apiInstance = createFunctionAPI('upload'); // 媒体上传使用上传服务器
    return apiInstance.post(`/vehicles/${vehicleId}/media`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
};

export const appAPI = {
  getSettings: () => api.get('/app/settings'),
  
  updateSettings: (settings: any) => api.put('/app/settings', settings),
  
  // 获取应用版本信息
  getVersion: () => api.get('/app/version'),
  
  // 检查更新
  checkUpdate: () => api.get('/app/check-update'),
};

// OpenAI API方法 - 专门用于汽车AI评分
export const openAIAPI = {
  // 汽车AI评分
  scoreVehicle: async (vehicleData: {
    brand: string;
    model: string;
    year: number;
    mileage: number;
    condition: string;
    price: number;
    description?: string;
    images?: string[];
  }) => {
    const prompt = `请对以下二手车进行专业评分（1-10分）并给出详细分析：

品牌：${vehicleData.brand}
型号：${vehicleData.model}
年份：${vehicleData.year}
里程：${vehicleData.mileage}公里
车况：${vehicleData.condition}
价格：${vehicleData.price}元
描述：${vehicleData.description || '无'}
图片数量：${vehicleData.images?.length || 0}张

请从以下维度进行评分：
1. 车况评分（1-10分）
2. 性价比评分（1-10分）
3. 市场价值评分（1-10分）
4. 综合评分（1-10分）

请用中文回复，格式如下：
车况评分：X分
性价比评分：X分
市场价值评分：X分
综合评分：X分

详细分析：[详细分析内容]

建议：[购买建议]`;

    try {
      const response = await axios.post(
        `${OPENAI_CONFIG.baseURL}/chat/completions`,
        {
          model: OPENAI_CONFIG.defaultModel,
          messages: [
            {
              role: 'system',
              content: '你是一个专业的汽车评估师，请根据提供的车辆信息给出专业的评分和建议。'
            },
            {
              role: 'user',
              content: `请评估以下车辆：品牌：${vehicleData.brand}，型号：${vehicleData.model}，年份：${vehicleData.year}，里程：${vehicleData.mileage}万公里。请给出1-100的评分和详细建议。`
            }
          ],
          max_tokens: OPENAI_CONFIG.maxTokens,
          temperature: OPENAI_CONFIG.temperature
        },
        {
          headers: {
            'Authorization': `Bearer ${OPENAI_CONFIG.apiKey}`,
            'Content-Type': 'application/json'
          },
          timeout: OPENAI_CONFIG.timeout
        }
      );

      return response.data;
    } catch (error) {
      console.error('OpenAI API调用失败:', error);
      throw error;
    }
  },

  // 汽车价格评估
  evaluatePrice: async (vehicleData: {
    brand: string;
    model: string;
    year: number;
    mileage: number;
    condition: string;
    marketPrice: number;
  }) => {
    const prompt = `请评估以下二手车的合理市场价格：

品牌：${vehicleData.brand}
型号：${vehicleData.model}
年份：${vehicleData.year}
里程：${vehicleData.mileage}公里
车况：${vehicleData.condition}
当前标价：${vehicleData.marketPrice}元

请给出：
1. 合理价格范围（最低价-最高价）
2. 价格分析
3. 议价建议

请用中文回复，格式如下：
合理价格范围：X元 - Y元
价格分析：[分析内容]
议价建议：[建议内容]`;

    try {
      const response = await axios.post(
        `${OPENAI_CONFIG.baseURL}/chat/completions`,
        {
          model: OPENAI_CONFIG.defaultModel,
          messages: [
            {
              role: 'user',
              content: prompt
            }
          ],
          max_tokens: OPENAI_CONFIG.maxTokens,
          temperature: OPENAI_CONFIG.temperature
        },
        {
          headers: {
            'Authorization': `Bearer ${OPENAI_CONFIG.apiKey}`,
            'Content-Type': 'application/json'
          },
          timeout: OPENAI_CONFIG.timeout
        }
      );

      return response.data;
    } catch (error) {
      console.error('OpenAI API调用失败:', error);
      throw error;
    }
  }
};

// 车辆相关API
export const carAPI = {
  // 获取车辆列表（分页）
  getCars: (page: number = 1, limit: number = 20, filters: any = {}) =>
    api.get('/api/cars', { params: { page, limit, ...filters } }),
  
  // 获取所有车辆（不分页，用于搜索）
  getAllCars: (filters: any = {}) =>
    api.get('/api/cars/all', { params: filters }),
  
  // 根据ID获取车辆详情
  getCarById: (id: string) =>
    api.get(`/api/cars/${id}`),
  
  // 添加新车辆
  addCar: (carData: any) =>
    api.post('/api/cars', carData),
  
  // 更新车辆信息
  updateCar: (id: string, carData: any) =>
    api.put(`/api/cars/${id}`, carData),
  
  // 删除车辆
  deleteCar: (id: string) =>
    api.delete(`/api/cars/${id}`),
};

export default api; 